package ext.tianma.masschange.util;

import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import java.util.Locale;
import java.util.Vector;

import org.json.JSONException;
import org.json.JSONObject;

import wt.change2.WTChangeActivity2;
import wt.fc.QueryResult;
import wt.fc.WTObject;
import wt.method.RemoteAccess;
import wt.part.Quantity;
import wt.part.QuantityUnit;
import wt.part.SubstituteQuantity;
import wt.part.WTPart;
import wt.part.WTPartMaster;
import wt.part.WTPartSubstituteLink;
import wt.part.WTPartUsageLink;
import wt.session.SessionHelper;
import wt.util.WTException;
import wt.util.WTMessage;
import wt.util.WTProperties;
import wt.vc.wip.WorkInProgressHelper;

import com.ptc.core.components.beans.TableDataManagerBean;
import com.ptc.netmarkets.model.NmOid;
import com.ptc.netmarkets.util.beans.NmCommandBean;

import ext.com.core.CoreUtil;

public class MassChangeProcessorUtil implements RemoteAccess,Serializable{
	
	private static String RESOURCE = "ext.tianma.masschange.resource.MassChangeResource";
	private static String CLASSNAME="";
	private static boolean VERBOSE = true;
	private static WTProperties wtProperties;
	private static Locale locale = null;

	static {

		try {
			CLASSNAME= MassChangeUtil.class.getName();
			wtProperties = WTProperties.getLocalProperties();
			locale = SessionHelper.manager.getLocale();
			VERBOSE = wtProperties.getProperty("ext.tianma.masschange.util.verbose", false);
		}
		catch (IOException ioe) {
			ioe.printStackTrace();
		}catch (Throwable throwable) {
			throw new ExceptionInInitializerError(throwable);
		}
	}
	
	public MassChangeProcessorUtil() {

	}
	  /**
	 *输出调试信息
	 */
	private static void outDebugInfo(String info) {
		if(VERBOSE)
			System.out.println(CLASSNAME+"......"+info);
	}
	
	/**
	 * 根据nmcommandbean获取JS封装的数据
	 * @param nmcommandbean
	 * @return
	 * @throws WTException 
	 */
	public static Vector getSelectedData(NmCommandBean nmcommandbean, String tableId) throws WTException {
		Vector lines = new Vector();
		TableDataManagerBean tabledatamanagerbean = TableDataManagerBean.newInstance(nmcommandbean);
	    List<NmOid>  nmoids = null;
    	try {
    		nmoids = tabledatamanagerbean.getOids(tableId);
    	} catch(Exception nmoidsExp) {	
    		nmoidsExp.printStackTrace();
    	}
    	if(nmoids!=null) {
    		int nmoidsListSize = nmoids.size(); 
    		for(int i=0 ; i < nmoidsListSize; i++ ){
    			Vector<Object> line = new Vector<Object>();
    			NmOid nmOid = nmoids.get(i);
    			outDebugInfo("nmOid="+nmOid);
    			if(nmOid!=null) {
    				Object parentListJSON = tabledatamanagerbean.getData("parentListJSON", tableId, nmOid);
    				if(parentListJSON!=null) {
    					if(parentListJSON instanceof JSONObject) {
    						JSONObject parentJSON = (JSONObject) parentListJSON;
    						try {
    							String pNumber = parentJSON.getString("pNumber");
        						String pView = parentJSON.getString("pView");
        						String pQuantity = getPQuantity(parentJSON);
        						String pUnit = getPUnit(parentJSON);
        						String pYield = getPYield(parentJSON); 
        						String plineNumber=getLineNumber(parentJSON);
        						
        						line.add(pNumber);
        						line.add(pView);
        						line.add(pQuantity);
        						line.add(pUnit);
        						line.add(pYield);
        						line.add(plineNumber);
        						lines.add(line);
        						
        						outDebugInfo("pNumber="+pNumber);
        						outDebugInfo("pView="+pView);
        						outDebugInfo("pQuantity="+pQuantity);
        						outDebugInfo("pUnit="+pUnit);
        						outDebugInfo("pYield="+pYield);
        						outDebugInfo("plineNumber="+plineNumber);
        						System.out.println("plineNumber="+plineNumber);
    						} catch (org.json.JSONException e) {
    							e.printStackTrace();
    						}
    						
    					}
    				}
    			}		
    		}
    	}
    	return lines;
	}
	
	/**
	 * 根据nmcommandbean获取JS封装的数据
	 * @param nmcommandbean
	 * @return
	 * @throws WTException 
	 */
	public static Vector getNoYieldSelectedData(NmCommandBean nmcommandbean, String tableId) throws WTException {
		Vector lines = new Vector();
		TableDataManagerBean tabledatamanagerbean = TableDataManagerBean.newInstance(nmcommandbean);
		
	    List<NmOid>  nmoids = null;
    	try {
    		nmoids = tabledatamanagerbean.getOids(tableId);
    	} catch(Exception nmoidsExp) {	
    		nmoidsExp.printStackTrace();
    	}
    	if(nmoids!=null) {
    		int nmoidsListSize = nmoids.size(); 
    		for(int i=0 ; i < nmoidsListSize; i++ ){
    			Vector line = new Vector();
    			NmOid nmOid = nmoids.get(i);
    			outDebugInfo("nmOid="+nmOid);
    			if(nmOid!=null) {
    				Object parentListJSON = tabledatamanagerbean.getData("parentListJSON2", tableId, nmOid);
    				if(parentListJSON!=null) {
    					if(parentListJSON instanceof JSONObject) {
    						JSONObject parentJSON = (JSONObject) parentListJSON;
    						try {
    							String pNumber = parentJSON.getString("pNumber");
        						String pView = parentJSON.getString("pView");
        						String pQuantity = getPQuantity(parentJSON);
        						String pUnit = getPUnit(parentJSON);   
        						
        						line.add(pNumber);
        						line.add(pView);
        						line.add(pQuantity);
        						line.add(pUnit);
        						lines.add(line);
        						
        						outDebugInfo("pNumber="+pNumber);
        						outDebugInfo("pView="+pView);
        						outDebugInfo("pQuantity="+pQuantity);
        						outDebugInfo("pUnit="+pUnit);
        					
    						} catch (org.json.JSONException e) {
    							e.printStackTrace();
    						}
    						
    					}
    				}
    			}		
    		}
    	}
    	return lines;
	}
	
	/**
	 * 从js封装的数据中获取行号
	 * @param parentJSON
	 * @return
	 * @throws JSONException
	 * @throws WTException
	 */
	
	private static String getLineNumber(JSONObject parentJSON) throws JSONException, WTException {
		String lineNumber="";
		
		if(parentJSON!=null){
			JSONObject plineNumberJSON = parentJSON.getJSONObject("pLineNumber");
			if(plineNumberJSON!=null){
				JSONObject pLineNumberJSON1 = plineNumberJSON.getJSONObject("gui");
				if(pLineNumberJSON1 !=null){
					String lineNumber1=pLineNumberJSON1.get("value").toString().trim();
					if(lineNumber!=null){
						if(MassChangeUtil.isNum(lineNumber)){
							lineNumber=lineNumber1;
						}else{
							throw new WTException("数量填写非数字");
						}
					}
				}
			}
		}
		return lineNumber;
	}
	/**
	 * 从js封装的JSON中获取数量
	 * @param parentJSON
	 * @return
	 * @throws JSONException
	 * @throws WTException
	 */
	public static String getPQuantity(JSONObject parentJSON) throws JSONException, WTException {
		String quantityStr = "1";
		if(parentJSON != null) {
			JSONObject pQuantityJSON = parentJSON.getJSONObject("pQuantity");
			if(pQuantityJSON!=null) {
				JSONObject pQuantityJSON1 = pQuantityJSON.getJSONObject("gui");
				if(pQuantityJSON1!=null) {
					String quantityStr1 = pQuantityJSON1.get("value").toString().trim();
					if(quantityStr1!=null) {
						if(MassChangeUtil.isNum(quantityStr1)) {
							quantityStr = quantityStr1;
						} else {
							throw new WTException("数量填写非数字");
						}
					}
				}
			}
		}
		return quantityStr;
	}
	
	/**
	 * 从js封装的JSON中获取单位
	 * @param parentJSON
	 * @return
	 * @throws JSONException
	 */
	public static String getPUnit(JSONObject parentJSON) throws JSONException {
		String unit = "";
		if(parentJSON != null) {
			JSONObject pUnitJSON = parentJSON.getJSONObject("pUnit");
			outDebugInfo("pUnitJSON="+pUnitJSON.toJSONString());
			if(pUnitJSON!=null) {
				JSONObject pUnitJSON1 = pUnitJSON.getJSONObject("gui");
				if(pUnitJSON1!=null) {
					Object obj = pUnitJSON1.get("comparable") ;
					if(obj instanceof String) {
						String unitStr = (String)obj;
						//只有单位为"每个"的时候会出现这个值
						if(unitStr.equalsIgnoreCase("[每个]")) {
							return "ea";
						} else if(unitStr.equalsIgnoreCase("[根据需要]")) {
							return "as_needed";
						} else if(unitStr.equalsIgnoreCase("[千克]")) {
							return "kg";
						} else if(unitStr.equalsIgnoreCase("[米]")) {
							return "m";
						} else if(unitStr.equalsIgnoreCase("[升]")) {
							return "l";
						} else if(unitStr.equalsIgnoreCase("[平方米]")) {
							return "sq_m";
						} else if(unitStr.equalsIgnoreCase("[立方米]")) {
							return "cu_m";
						} else if(unitStr.equalsIgnoreCase("[EAE]")) {
							return "EAE";
						} else if(unitStr.equalsIgnoreCase("[PCS]")) {
							return "PCS";
						} else if(unitStr.equalsIgnoreCase("[CUB]")) {
							return "CUB";
						} else if(unitStr.equalsIgnoreCase("[G]")) {
							return "G";
						} else if(unitStr.equalsIgnoreCase("[MG]")) {
							return "MG";
						} else if(unitStr.equalsIgnoreCase("[M]")) {
							return "M";
						} else if(unitStr.equalsIgnoreCase("[MM]")) {
							return "MM";
						} else if(unitStr.equalsIgnoreCase("[MPC]")) {
							return "MPC";
						} else if(unitStr.equalsIgnoreCase("[PIN]")) {
							return "PIN";
						} else if(unitStr.equalsIgnoreCase("[SHT]")) {
							return "SHT";
						} else if(unitStr.equalsIgnoreCase("[SET]")) {
							return "SET";
						} else if(unitStr.equalsIgnoreCase("[PAG]")) {
							return "PAG";
						} else {
							String[] unitSplit = unitStr.split("\\.");
							unit = unitSplit[3];
						}
					}
						
				}
			}
		}
		return unit;
	}
	
	/**
	 * 从js封装的JSON中获取良率
	 * @param parentJSON
	 * @return
	 * @throws JSONException
	 * @throws WTException
	 */
	public static String getPYield(JSONObject parentJSON) throws JSONException {
		String Yield = "";
		if(parentJSON != null) {
			JSONObject pYieldJSON = parentJSON.getJSONObject("pYield");
			if(pYieldJSON!=null) {
				JSONObject pYieldJSON1 = pYieldJSON.getJSONObject("gui");
				if(pYieldJSON1!=null) {
					Yield = pYieldJSON1.get("value").toString().trim();
				}
			}
		}
		return Yield;
	}
	
	/**
	 * 获取表格中的父件,并检出或修订检出
	 * @param line
	 * @return
	 * @throws WTException
	 */
	public static WTPart getCheckoutParent(String number, String view, WTChangeActivity2 ca) throws WTException {			
		WTPart parent = CoreUtil.getWTPartByNumberAndView(number, view);
		
		WTPart checkoutParent = null;
		WTPart workCopyParent = null;
		//新品”或“量产发布”状态，则对父件进行修订
		boolean inCurrentCA = MassChangeUtil.inCurrentCA(parent,ca);
		if((MassChangeUtil.equalState(parent, "NewProduct") || MassChangeUtil.equalState(parent, "MassProductionRelease"))&& !inCurrentCA) {
			WTPart revisePart = MassChangeUtil.revisePart(parent);
			
			if(MassChangeUtil.equalState(parent, "NewProduct")){
				MassChangeUtil.setState(revisePart, "NewProduct");
			} else if (MassChangeUtil.equalState(parent, "MassProductionRelease")) {
				MassChangeUtil.setState(revisePart, "MassProductionRelease");
			}
			checkoutParent = (WTPart) CoreUtil.checkoutObject(revisePart);
			//revisePartCheckout
		} else {
			checkoutParent = (WTPart) CoreUtil.checkoutObject(parent);
		}
		if(!WorkInProgressHelper.isWorkingCopy(checkoutParent)) {
			workCopyParent = (WTPart) WorkInProgressHelper.service.workingCopyOf(checkoutParent);
		} else {
			workCopyParent = checkoutParent;
		}

		return workCopyParent;
	}
	
	/**
	 * 获取rsource信息
	 * @param key
	 * @return
	 */
	public static String getMessage(String key) {
		String value = "";
		value = WTMessage.getLocalizedMessage(RESOURCE, key, null, locale);
		return value;
	}
	
	/**
	 * 根据nmcommandbean获取当前CA
	 * @param nmcommandbean
	 * @return
	 * @throws WTException
	 */
	public static WTChangeActivity2 getCA(NmCommandBean nmcommandbean) throws WTException {
		NmOid nmoid = nmcommandbean.getActionOid();
	    WTObject contextObj = (WTObject) nmoid.getWtRef().getObject();
	    WTChangeActivity2 ca = null; 
	    if(contextObj instanceof WTChangeActivity2) {
	    	ca = (WTChangeActivity2)contextObj;
	    }
	    return ca;
	}
	
	/**
	 * 记录WTPartUsageLink当前的使用关系和所有替代关系
	 * @param usageLink
	 * @return
	 * @throws WTException
	 */
	public static Vector getOldLinkValues(WTPartUsageLink usageLink) throws WTException {
		Vector values = new Vector();
		Vector uselinkValue = new Vector();
		uselinkValue.add(getLinkValue(usageLink));
		QueryResult qr = MassChangeUtil.getPartSubstituteLinks(usageLink);
		while(qr.hasMoreElements()) {
			WTPartSubstituteLink substituteLink = (WTPartSubstituteLink)qr.nextElement();
			Vector substituteValue =  getLinkValue(substituteLink);
			values.add(substituteValue);
		}	
		return values;		
	}
	
	/**
	 * 获取usageLink的信息
	 * @param usageLink
	 * @return
	 */
	public static Vector getLinkValue(WTPartUsageLink usageLink) {
		Vector vc = new Vector();
		WTPartMaster master = usageLink.getUses();
		Quantity quantity = usageLink.getQuantity();
		double amout = quantity.getAmount();
		QuantityUnit unit = quantity.getUnit();
		vc.add(master);
		vc.add(amout);
		vc.add(unit);
		return vc;
	}
	
	/**
	 * 获取substituteLink的信息
	 * @param substituteLink
	 * @return
	 */
	public static Vector getLinkValue(WTPartSubstituteLink substituteLink) {
		Vector vc = new Vector();
		WTPartMaster master = substituteLink.getSubstitutes();
		SubstituteQuantity quantity = substituteLink.getQuantity();
		double amount = quantity.getAmount();
		QuantityUnit unit = quantity.getUnit();
		vc.add(master);
		vc.add(amount);
		vc.add(unit);
		return vc;
	}
}
